<template>
  <div class="form-address">
    <div class="form-address-picker bbx-form-cell-item">
      <base-dist-picker :disabled="disabled" @input="handleCitySelectorChange" :value="distValue" :placeholder="placeholder"/>
      <el-button type="plain-third" @click="chooseMap" v-if="!disableMap" class="action-btn" :disabled="disabled">{{$t('common.form.preview.address.choosAddressInMap')}}</el-button>
    </div>
    <div class="form-address-picker bbx-form-cell-item" v-if="!toggle">
      <input
        type="text"
        :value="detail"
        @input="input"
        :maxlength="maxlength"
        :disabled="disabled"
        :id="`form_${field.fieldName}`"
        autocomplete="off"
        :placeholder="$t('common.placeholder.inputDetailAddress')"
      />
      <el-button type="plain-third" class="action-btn" :disabled="disabled" @click="toggleModal">{{$t('common.form.preview.address.resolve')}}</el-button>
    </div>
    
    <base-modal :show.sync="visible" :title="$t('common.form.preview.address.resolve')" class="form-address-modal">
      <textarea v-model.trim="copy" :placeholder="$t('common.form.preview.address.copyTips')" maxlength="1000"></textarea>
      <el-button type="primary" @click="analyze" :disabled="!copy.length || pending">{{$t('common.base.parse')}}</el-button>
    </base-modal>
  </div>
</template>

<script>
import FormMixin from '@src/component/form/mixin/form';
import addressParseMixin from './mixin';
import { FORM_FIELD_TEXT_MAX_LENGTH } from '@src/model/const/Number.ts';

export default {
  name: 'form-address',
  mixins: [FormMixin,addressParseMixin],
  props: {
    addressBackup: {
      type: Object,
      default: () => ({})
    },  
    value: {
      type: Object,
      default(){
        let value = {
          /**
           * value值必须包含以下值:
           * province: String,
           * city: String,
           * dist: String,
           * address: String
           * 
           * 以下值可选：
           * latitude： [String,Number],
           * longitude: [String,Number],
           * addressType: Number
           */
        };
          
        return value
      }
    },
    /** 是否启禁用图选址 */
    disableMap: {
      type: Boolean,
      default: false
    },
    // 工单客户关联字段清除位置信息时候不调用update
    taskDisableUpdate: {
      type: Boolean,
      default: false
    },
    // 是否展示解析地址
    toggle: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      maxlength: FORM_FIELD_TEXT_MAX_LENGTH
    }
  },
  computed: {
    /** 将省市区转换成数组 */
    distValue(){
      let {province, city, dist} = this.value;
      if(!province) return [];

      let arr = [province];
      if(!city) return arr;
        
      arr.push(city);
      if(dist) arr.push(dist)

      return arr;
    },
    /** 详细地址 */
    detail(){
      return this.value.address;
    }
  },
  mounted() {
  },
  methods: {
    
    input(event) {
      let newAddress = {
        ...this.value,
        address: event.target.value
      };

      let adrBackup = this.addressBackup;
      newAddress.addressType = this.diffAddress(newAddress, adrBackup);

      if (newAddress.addressType) {
        newAddress.latitude = adrBackup.adLatitude || adrBackup.latitude;
        newAddress.longitude = adrBackup.adLongitude || adrBackup.longitude;
      } else {
        newAddress.latitude = '';
        newAddress.longitude = '';
      }

      this.updateValue(newAddress)
    },
    diffAddress(newVal, oldVal) {
      let newAdr = (newVal.adProvince || newVal.province) + (newVal.adCity || newVal.city) + (newVal.adDist || newVal.dist) + (newVal.adAddress || newVal.address);
      let oldAdr = (oldVal.adProvince || oldVal.province) + (oldVal.adCity || oldVal.city) + (oldVal.adDist || oldVal.dist) + (oldVal.adAddress || oldVal.address);

      return Number(newAdr === oldAdr);
    },
    handleCitySelectorChange(val) {
      let newAddress = {
        province: '',
        city: '',
        dist: '',
        address: ''
      };

      if(!Array.isArray(val) || !val.length) {
        return this.updateValue(newAddress);
      }

      newAddress = {
        ...this.value,
        province: val[0] || '',
        city: val[1] || '',
        dist: val[2] || '',
      };

      let adrBackup = this.addressBackup;
      newAddress.addressType = this.diffAddress(newAddress, adrBackup);


      if (newAddress.addressType) {
        newAddress.latitude = adrBackup.adLatitude || adrBackup.latitude;
        newAddress.longitude = adrBackup.adLongitude || adrBackup.longitude;
      }

      this.updateValue(newAddress);
    },
    updateValue(newValue) {
      let oldValue = null;
      // 工单客户关联字段清除位置信息时候不调用update
      if(!this.taskDisableUpdate){
        this.$emit('update', {newValue, oldValue, field: this.field});
      }
      this.$emit('input', newValue);
    },
    chooseMap() {
      const point = {
        latitude: this.value.latitude || '',
        longitude: this.value.longitude || '',
      };

      let defaultArea = this.value.province;
      // TODO 国际化待办
      if(this.value.city && ['郊县', '市辖区', '其他'].indexOf(this.value.city) < 0) defaultArea = this.value.city;
      if(this.value.dist) defaultArea = this.value.dist; 

      // 有经纬度用经纬度，没有使用较小的行政单位
      this.$fast.map.picker(point, {defaultArea}).then(result => {
        if (result.status === 1) return;

        let adr = result.data;
        adr.addressType = 1;

        this.$emit('update-address-backup', adr);
        this.updateValue(adr);
      })
        .catch(err => console.error(err));
    },
    getValue(){
      return this.value;
    }
  }
}
</script>

<style lang="scss">
.form-address {
  input {
    width: 100%;
  }

  .el-input__inner:hover {
    border-color: $color-primary;
  }

  .base-dist-picker {
    flex-grow: 1;
    .el-cascader {
      width: 100%;
    }
  }


  .form-address-modal {

    .base-modal-body {
      padding: 20px;
      display: flex;
      justify-content: flex-end;
      flex-wrap: wrap;

      textarea {
        flex-shrink: 0;
        line-height: 24px;
        height: 48px;
        width: 100%;
        resize: none;
      }

      .el-button {
        margin-top: 10px;
      }

    }
  }
}

.form-address-picker{
  display: flex;
  justify-content: space-between;

  .form-address-picker {
    margin-top: 10px;
  }

  .form-item, .form-text {
    width: 400px;
  }

  .action-btn {
    margin-left: 10px;
  }
}
</style>
